package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.query.QueryForObject;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("menu")
public class MenuController {
    @Autowired
    private IMenuService menuService;

    @RequiresPermissions("menu:index")
    @PermissionName("菜单主页")
    @RequestMapping("index")
    public String index() {
        return "menu/list";
    }

    @RequiresPermissions("menu:list")
    @PermissionName("菜单列表")
    @RequestMapping("list")
    @ResponseBody
    //分页显示
    public PageResult list(QueryForObject qo){
        return menuService.query(qo);
    }

    @RequestMapping("queryRootMenu")
    @ResponseBody
    public List<Menu> queryRootMenu(){
        //从session中获取登录成功之后缓存的菜单
        return menuService.queryRootMenu();
    }
    @RequiresPermissions("menu:save")
    @PermissionName("菜单保存")
    @RequestMapping("save")
    @ResponseBody
    public JsonResult save(Menu entity){
        JsonResult result = new JsonResult();
        try {
            menuService.save(entity);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("保存菜单失败");
        }
        return result;
    }

    @RequiresPermissions("menu:update")
    @PermissionName("菜单编辑")
    @RequestMapping("update")
    @ResponseBody
    public JsonResult update(Menu entity){
        JsonResult result = new JsonResult();
        try {
            menuService.update(entity);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("编辑菜单失败");
        }
        return result;
    }
    @RequiresPermissions("menu:delete")
    @PermissionName("菜单删除")
    @RequestMapping("delete")
    @ResponseBody
    public JsonResult delete(Long id){
        JsonResult result = new JsonResult();
        try {
            //判断是否是父级=菜单
            if(id!=null){
                menuService.delete(id);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("请先删除当前父级菜单下所有的子菜单");
        }
        return result;
    }
}